package com.ymt.bpm.web.action.biz;

import com.ymt.bpm.appboot.BpmpProperties;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.AES;
import com.ymt.bpm.util.EncodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Johnny on 2017/4/18.
 */
@Controller
@RequestMapping(path="/view/bizdata")
@EnableConfigurationProperties(BpmpProperties.class)
public class BizDataJspController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Environment env;

    @Autowired
    private BpmpProperties bpmp;

    private String formCdnPath = null;

    /**
     * 业务编辑页面
     * @param request
     * @param response
     * @param formid
     * @param versionid
     * @return
     */
    @GetMapping(path="/edit/{formid}/{versionid}", produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView edit(HttpServletRequest request,
                             HttpServletResponse response,
                             @PathVariable("formid")String formid,
                             @PathVariable("versionid")String versionid) {
        Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String tenantId = userDetail.get(Const.TENANT_ID);
        String loginName = userDetail.get(Const.LOGINNAME);
        String displayName = userDetail.get(Const.DISPLAYNAME);
        String lang = userDetail.get(Const.LANG);
        formid = EncodeUtil.decodeEncodedBase64(formid);
        versionid = EncodeUtil.decodeEncodedBase64(versionid);
        if (log.isDebugEnabled()) {
            log.debug("edit formid:"+formid);
            log.debug("edit versionid:"+versionid);
            log.debug("edit tenantId:"+tenantId);
            log.debug("edit lang:"+lang);
        }
        String path = "/jsp/bizdata/edit.jsp";
        if ("cdn".equalsIgnoreCase(bpmp.getFormLocation())) {
            path = "platform/bizdata/edit";
        }
        ModelAndView view = baseView(request, path);

        view.addObject(Const.LOGINNAME, loginName);
        view.addObject(Const.DISPLAYNAME, displayName);
        String formfileName = getFormName(lang, formid, versionid);
        String formfile = getFormPath(tenantId, formfileName);
        view.addObject("formfileName", formfileName);
        view.addObject("formfile", formfile);
        if (!"cdn".equalsIgnoreCase(bpmp.getFormLocation())) {
            String contextRealPath = request.getServletContext().getRealPath("/");
            String realPath = contextRealPath.replace("\\", "/") + formfile.substring(1);
            if (log.isDebugEnabled()) {
                log.debug("edit formfile=" + formfile);
                log.debug("edit realPath=" + realPath);
            }
            File file = new File(realPath);
            if (!file.exists()) {
                view.setViewName("/html/error-msg.jsp?msg=FORMFILE_NOTFOUND");
                //view.addObject("msg", "FORMFILE_NOTFOUND");
                return view;
            }
        }

        //generate an id
        view.addObject("newTsId", "ID-"+ UUID.randomUUID());
        view.addObject("formCdnPath", getFormCdnPath(tenantId));
        view.addObject("fmdCtx", env.getProperty("fmd.ctx"));

        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        return view;
    }

    /*@GetMapping(path="/formpage/{formid}/{versionid}", produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView formpage(HttpServletRequest request,
                                 @PathVariable("formid")String formid,
                                 @PathVariable("versionid")String versionid) {

        String tenantId = userDetail.get(Const.TENANT_ID);
        String lang = userDetail.get(Const.LANG);
        formid = EncodeUtil.decodeEncodedBase64(formid);
        versionid = EncodeUtil.decodeEncodedBase64(versionid);
        if (log.isDebugEnabled()) {
            log.debug("formpage formid:"+formid);
            log.debug("formpage versionid:"+versionid);
            log.debug("formpage tenantId:"+tenantId);
            log.debug("formpage lang:"+lang);
        }

        String formfileName = getFormName(lang, formid, versionid);
        String formfile = getFormPath(tenantId, formfileName);
        ModelAndView view = new ModelAndView(formfile);

        //redirect other parameters
        Enumeration<String> paramEnu = request.getParameterNames();
        while(paramEnu.hasMoreElements()) {
            String param = paramEnu.nextElement();
            view.addObject(param, request.getParameter(param));
        }

        String[] profile = env.getActiveProfiles();
        String productionVersion = env.getProperty("bpmp.production-version", "0");
        String cdn = env.getProperty("bpmp.cdn", "/bpmp-resources");
        view.addObject("profile", profile[0]);
        view.addObject("productionVersion", productionVersion);
        view.addObject("cdn", cdn);
        view.addObject(Const.LANG, lang);

        return view;
    }*/

    private ModelAndView baseView(HttpServletRequest request, String path) {
        ModelAndView view = new ModelAndView(path);

        Enumeration<String> paramEnu = request.getParameterNames();
        while(paramEnu.hasMoreElements()) {
            String param = paramEnu.nextElement();
            view.addObject(param, request.getParameter(param));
        }

        Map<String, String> userDetail = (Map<String, String>)SecurityContextHolder.getContext().getAuthentication().getDetails();
        String lang = userDetail.get(Const.LANG);
        String[] profile = env.getActiveProfiles();
        String productionVersion = env.getProperty("bpmp.production-version", "0");
        String cdn = env.getProperty("bpmp.cdn", "/bpmp-resources");

        view.addObject("profile", profile[0]);
        view.addObject("productionVersion", productionVersion);
        view.addObject("cdn", cdn);
        view.addObject(Const.LANG, lang);

        return view;
    }

    private String getFormPath(String tenantId, String formfileName) {
        String tenantSubDir = tenantId == null ? "0/" : tenantId+"/";
        String formfile = "/jsp/forms/" + tenantSubDir +
                formfileName + ".jsp";
        if (log.isDebugEnabled()) {
            log.debug("formfile:"+formfile);
        }
        return formfile;
    }

    private String getFormName(String lang, String formid, String versionid) {
        String formskin = env.getProperty("bpmp.formskin");
        String formfileName = formid + "-" +
                versionid + "-" + lang + "-" + formskin;
        if (log.isDebugEnabled()) {
            log.debug("formfileName:"+formfileName);
        }
        return formfileName;
    }

    private String getFormCdnPath(String tenantId) {
        if (formCdnPath==null) {
            formCdnPath = env.getProperty("oss.form.schema") +
                    env.getProperty("oss.form.bucket-name") + "." +
                    env.getProperty("oss.form.endpoint") + "/forms/";
        }
        String rtn = formCdnPath;
        if (tenantId==null || tenantId.length()==0) {
            rtn += AES.encrypt("0");
        } else {
            rtn += AES.encrypt(tenantId);
        }
        rtn += "/dataedit/inline/";
        return rtn;
    }

}
